package com.example.myapplication.ip;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.widget.EditText;
import androidx.annotation.Nullable;
import androidx.core.os.HandlerCompat;
import com.example.myapplication.R;
import com.example.util.NetWorkUtil;
import com.example.util.ToastUtil;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class AddressView extends Activity {
    private EditText addressEditView;
    private EditText portEditView;

    private static Executor executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.MINUTES, new LinkedBlockingQueue(4));
    private final Handler resultHandler = HandlerCompat.createAsync(Looper.getMainLooper());

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_adress);
        initView();
    }

    private void initView() {
        //初始化
        addressEditView = this.findViewById(R.id.addressEdit);
        portEditView = this.findViewById(R.id.portEdit);

        //
        addressEditView.setOnFocusChangeListener((v, hasFocus) -> {
            if(hasFocus) return;
            handleAddressEditView((EditText) v);
        });
    }

    private void handleAddressEditView(EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) return;
            Editable address = ((EditText) v).getText();
            if (address == null || address.toString().length() == 0) {
                ToastUtil.show(this, "请输入地址");
                return;
            }
            executor.execute(() -> {
                if (!NetWorkUtil.isAvailable(address.toString())) {
                    resultHandler.post(() -> {
                        ToastUtil.show(this, "ip地址连接失败,请检查");
                    });
                }
            });



        });
    }

}
